<template>
	<view class="device-connect">
		<u-navbar title="设备连接" :is-back="true" :border-bottom="false"></u-navbar>
		
		<view class="container">
			<!-- 设备信息卡片 -->
			<view class="device-card">
				<view class="device-icon">
					<u-icon name="phone-fill" size="80" color="#ffda33"></u-icon>
				</view>
				<view class="device-status" :class="{ connected: isConnected }">
					<text>{{ isConnected ? '已连接' : '未连接' }}</text>
				</view>
			</view>
			
			<!-- 设备信息表单 -->
			<view class="form-section">
				<view class="form-item">
					<text class="label">设备ID</text>
					<u-input v-model="deviceId" placeholder="请输入设备唯一标识" :disabled="isConnected"></u-input>
				</view>
				
				<view class="form-item">
					<text class="label">设备名称</text>
					<u-input v-model="deviceName" placeholder="请输入设备名称（可选）"></u-input>
				</view>
				
				<view class="form-item">
					<text class="label">设备类型</text>
					<u-input v-model="deviceType" placeholder="如：usb、bluetooth、serial"></u-input>
				</view>
				
				<view class="form-item">
					<text class="label">手机号</text>
					<u-input v-model="phone" placeholder="请输入手机号" type="number" maxlength="11"></u-input>
					<text class="tip">如果设备已绑定，将自动使用绑定的手机号</text>
				</view>
			</view>
			
			<!-- 操作按钮 -->
			<view class="action-section">
				<u-button 
					type="primary" 
					:loading="isConnecting"
					@click="handleConnect"
					:disabled="!deviceId || isConnected"
				>
					{{ isConnected ? '已连接' : '连接设备并获取验证码' }}
				</u-button>
				
				<u-button 
					v-if="isConnected"
					type="warning" 
					@click="handleDisconnect"
					style="margin-top: 20rpx;"
				>
					断开连接
				</u-button>
			</view>
			
			<!-- 验证码显示区域 -->
			<view v-if="authCode" class="auth-code-section">
				<view class="code-title">验证码</view>
				<view class="code-display">
					<text class="code-text">{{ authCode }}</text>
				</view>
				<view class="code-tip">验证码已发送到手机：{{ phone }}</view>
			</view>
			
			<!-- 设备绑定区域 -->
			<view v-if="isConnected && deviceInfo" class="bind-section">
				<view class="bind-title">设备绑定</view>
				<view class="bind-info">
					<text>设备名称：{{ deviceInfo.deviceName }}</text>
					<text>绑定手机：{{ deviceInfo.phone || '未绑定' }}</text>
					<text>最后连接：{{ formatTime(deviceInfo.lastConnectTime) }}</text>
				</view>
				
				<view class="bind-actions">
					<u-button 
						v-if="!deviceInfo.phone"
						type="success" 
						size="small"
						@click="showBindDialog = true"
					>
						绑定手机号
					</u-button>
					<u-button 
						v-else
						type="error" 
						size="small"
						@click="handleUnbind"
					>
						解绑
					</u-button>
				</view>
			</view>
		</view>
		
		<!-- 绑定手机号弹窗 -->
		<u-modal 
			v-model="showBindDialog" 
			title="绑定手机号"
			:show-cancel-button="true"
			@confirm="handleBind"
		>
			<view class="bind-dialog">
				<u-input 
					v-model="bindPhone" 
					placeholder="请输入手机号" 
					type="number"
					maxlength="11"
				></u-input>
			</view>
		</u-modal>
		
		<!-- 提示信息 -->
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
import $api from '../../api/user.js';

export default {
	data() {
		return {
			deviceId: '',
			deviceName: '',
			deviceType: 'usb',
			phone: '',
			isConnected: false,
			isConnecting: false,
			authCode: '',
			deviceInfo: null,
			showBindDialog: false,
			bindPhone: ''
		}
	},
	onLoad(options) {
		// 如果从外部传入设备ID，自动填充
		if (options.deviceId) {
			this.deviceId = options.deviceId;
		}
		if (options.phone) {
			this.phone = options.phone;
		}
		
		// 尝试自动连接（如果设备ID已存在）
		if (this.deviceId) {
			this.loadDeviceInfo();
		}
	},
	methods: {
		// 连接设备并获取验证码
		async handleConnect() {
			if (!this.deviceId || this.deviceId.trim() === '') {
				this.$refs.uToast.show({
					title: '请输入设备ID',
					type: 'error'
				});
				return;
			}
			
			this.isConnecting = true;
			
			try {
				const res = await $api.deviceConnect({
					deviceId: this.deviceId,
					deviceName: this.deviceName || undefined,
					deviceType: this.deviceType || undefined,
					phone: this.phone || undefined
				});
				
				console.log('设备连接响应', res);
				
				if (res.data && res.data.code === 200) {
					const data = res.data.data;
					
					if (data.success) {
						this.isConnected = true;
						this.phone = data.phone || this.phone;
						
						// 显示验证码（开发环境）
						if (data.code) {
							this.authCode = data.code;
						}
						
						this.$refs.uToast.show({
							title: data.message || '连接成功，验证码已发送',
							type: 'success'
						});
						
						// 加载设备信息
						this.loadDeviceInfo();
						
					} else {
						// 需要绑定手机号
						if (data.needBind) {
							this.showBindDialog = true;
						}
						
						this.$refs.uToast.show({
							title: data.message || '连接失败',
							type: 'error'
						});
					}
				} else {
					this.$refs.uToast.show({
						title: res.data.message || '连接失败',
						type: 'error'
					});
				}
			} catch (err) {
				console.error('设备连接失败', err);
				this.$refs.uToast.show({
					title: '连接失败，请重试',
					type: 'error'
				});
			} finally {
				this.isConnecting = false;
			}
		},
		
		// 断开连接
		handleDisconnect() {
			this.isConnected = false;
			this.authCode = '';
			this.deviceInfo = null;
			this.$refs.uToast.show({
				title: '已断开连接',
				type: 'success'
			});
		},
		
		// 加载设备信息
		async loadDeviceInfo() {
			if (!this.deviceId) return;
			
			try {
				const res = await $api.getDeviceInfo({
					deviceId: this.deviceId
				});
				
				if (res.data && res.data.code === 200) {
					this.deviceInfo = res.data.data;
					if (this.deviceInfo && this.deviceInfo.status === 1) {
						this.isConnected = true;
					}
				}
			} catch (err) {
				console.error('加载设备信息失败', err);
			}
		},
		
		// 绑定手机号
		async handleBind() {
			if (!this.bindPhone || !this.bindPhone.match(/^1[3-9]\d{9}$/)) {
				this.$refs.uToast.show({
					title: '请输入正确的手机号',
					type: 'error'
				});
				return;
			}
			
			try {
				const res = await $api.bindDevice({
					deviceId: this.deviceId,
					phone: this.bindPhone
				});
				
				if (res.data && res.data.code === 200) {
					this.showBindDialog = false;
					this.phone = this.bindPhone;
					this.bindPhone = '';
					
					this.$refs.uToast.show({
						title: '绑定成功',
						type: 'success'
					});
					
					// 重新连接获取验证码
					this.handleConnect();
				} else {
					this.$refs.uToast.show({
						title: res.data.message || '绑定失败',
						type: 'error'
					});
				}
			} catch (err) {
				console.error('绑定失败', err);
				this.$refs.uToast.show({
					title: '绑定失败，请重试',
					type: 'error'
				});
			}
		},
		
		// 解绑设备
		async handleUnbind() {
			uni.showModal({
				title: '确认解绑',
				content: '确定要解绑此设备吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							const result = await $api.unbindDevice({
								deviceId: this.deviceId
							});
							
							if (result.data && result.data.code === 200) {
								this.$refs.uToast.show({
									title: '解绑成功',
									type: 'success'
								});
								
								this.loadDeviceInfo();
							} else {
								this.$refs.uToast.show({
									title: result.data.message || '解绑失败',
									type: 'error'
								});
							}
						} catch (err) {
							console.error('解绑失败', err);
							this.$refs.uToast.show({
								title: '解绑失败，请重试',
								type: 'error'
							});
						}
					}
				}
			});
		},
		
		// 格式化时间
		formatTime(timeStr) {
			if (!timeStr) return '未知';
			const date = new Date(timeStr);
			return date.toLocaleString('zh-CN');
		}
	}
}
</script>

<style lang="scss" scoped>
.device-connect {
	min-height: 100vh;
	background-color: #f5f5f5;
}

.container {
	padding: 30rpx;
}

.device-card {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	border-radius: 20rpx;
	padding: 60rpx 40rpx;
	text-align: center;
	margin-bottom: 30rpx;
	
	.device-icon {
		margin-bottom: 20rpx;
	}
	
	.device-status {
		color: #fff;
		font-size: 32rpx;
		font-weight: bold;
		
		&.connected {
			color: #ffda33;
		}
	}
}

.form-section {
	background: #fff;
	border-radius: 20rpx;
	padding: 40rpx;
	margin-bottom: 30rpx;
	
	.form-item {
		margin-bottom: 30rpx;
		
		.label {
			display: block;
			font-size: 28rpx;
			color: #333;
			margin-bottom: 15rpx;
			font-weight: 500;
		}
		
		.tip {
			display: block;
			font-size: 24rpx;
			color: #999;
			margin-top: 10rpx;
		}
	}
}

.action-section {
	margin-bottom: 30rpx;
}

.auth-code-section {
	background: #fff;
	border-radius: 20rpx;
	padding: 40rpx;
	margin-bottom: 30rpx;
	text-align: center;
	
	.code-title {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 20rpx;
	}
	
	.code-display {
		background: linear-gradient(135deg, #ffda33 0%, #ffb347 100%);
		border-radius: 15rpx;
		padding: 40rpx;
		margin-bottom: 20rpx;
		
		.code-text {
			font-size: 60rpx;
			font-weight: bold;
			color: #333;
			letter-spacing: 10rpx;
		}
	}
	
	.code-tip {
		font-size: 24rpx;
		color: #999;
	}
}

.bind-section {
	background: #fff;
	border-radius: 20rpx;
	padding: 40rpx;
	
	.bind-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
	}
	
	.bind-info {
		display: flex;
		flex-direction: column;
		gap: 15rpx;
		margin-bottom: 20rpx;
		
		text {
			font-size: 28rpx;
			color: #666;
		}
	}
	
	.bind-actions {
		display: flex;
		justify-content: flex-end;
	}
}

.bind-dialog {
	padding: 20rpx;
}
</style>

